package com.na.game.engine.opengl;

import javax.microedition.khronos.opengles.GL10;

import android.graphics.Bitmap;
import android.opengl.GLUtils;

import com.na.game.engine.graphics.Image;

public class GLImage extends Image {

	private int width, height;
	private int preferredWidth, preferredHeight;
	private boolean recycled;
	private boolean recyclable = true;
	
	public GLImage(Bitmap bitmap, String name) {
		super(bitmap, name);
	}
	
	protected void bind(GL10 gl, int offsetx, int offsety) {
		if (bitmap != null) {
			GLUtils.texSubImage2D(GL10.GL_TEXTURE_2D, 0, offsetx, offsety, bitmap, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE);
			getWidth();
			getHeight();
			if (recyclable) {
				bitmap.recycle();
				bitmap = null;
			}
		}
	}

	@Override
	public boolean isRecycled() {
		return recycled;
	}
	
	@Override
	public void destroy() {
		recycled = true;
		super.destroy();
	}

	@Override
	public int getWidth() {
		if (width == 0 && bitmap != null) {
			width = bitmap.getWidth();
		}
		return width;
	}

	@Override
	public int getHeight() {
		if (height == 0 && bitmap != null) {
			height = bitmap.getHeight();
		}
		return height;
	}
	
	protected int getPreferredWidth() {
		if (preferredWidth == 0 && bitmap != null) {
			preferredWidth = pow2(getWidth());
		}
		return preferredWidth;
	}
	
	protected int getPreferredHeight() {
		if (preferredHeight == 0 && bitmap != null) {
			preferredHeight = pow2(getHeight());
		}
		return preferredHeight;
	}
	
	private int pow2(int num) {
		int size = 30;
		while (size > 0) {
			int bit = num >> size & 0x1;
			if (bit != 0) {
				break;
			}
			size--;
		}
		
		int n = 1 << size;
		if (n < num) {
			n = 1 << 1 + size;
		}
		
		return n;
	}
	
	public void setRecyclable(boolean recyclable) {
		this.recyclable = recyclable;
	}

}
